package com.atguigu.gulimall.product.thread;

import java.util.concurrent.*;

/**
 * @description:
 * @author: BlueSky
 * @create: 2022-04-11 10:46
 **/
public class ThreadTest {
	// public static ExecutorService executorService = Executors.newFixedThreadPool(10);
	public static void main(String[] args) throws ExecutionException, InterruptedException {
		/**
		 * 1、继承Thread
		 *		Thread01 thread01 = new Thread01();
		 * 		thread01.start();//启动线程
		 * 2、实现Runnable
		 * 		Runable01 runable01 = new Runable01();
		 * 		new Thread(runable01).start();
		 * 3、实现Callable接口 + FutureTask（可以拿到返回结果，可以处理异常）
		 *		FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
		 * 		new Thread(futureTask).start();
		 * 		Integer integer = futureTask.get();
		 * 4、线程池
		 * 		任务直接提交至线程池。
		 * 区别：
		 * 		1、2不能得到返回值。3可以得到返回值
		 * 		1、2、3不能控制资源
		 * 		4、可以控制资源，性能稳定。
		 */
		//123启动线程方式都不用，原因是启动线程不可控制，当线程过多时会导致资源浪费，系统崩溃的风险
		//当前系统中保证线程池只有一两个，每个异步任务，提交给线程池去自己执行
		// executorService.execute(new Runable01());
		// ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,
		// 		200,
		// 		10,
		// 		TimeUnit.SECONDS,
		// 		new LinkedBlockingDeque<>(100000),
		// 		Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
		// CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
		// 	int i = 10 / 0;
		// 	return i;
		// }, executorService);
		// CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
		// 	return "Hello";
		// }, executorService);

		//无返回值
		// future01.runAfterBothAsync(future02,()->{
		// 	System.out.println("任务3");
		// },executorService);
		//能接收f1,f2返回结果，自身无返回值
		// future01.thenAcceptBothAsync(future02,(f1,f2)->{
		// 	System.out.println("任务3："+f1+f2);
		// },executorService);
		//能接收f1,f2返回结果，自身有返回值

		// CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future01, future02);
		// completableFuture.get();//等待所有任务执行完才继续执行后续代码


	}

	//继承Thread
	public static class Thread01 extends Thread{
		@Override
		public void run(){
			System.out.println("当前线程："+Thread.currentThread().getId());
			int i = 10/2;
			System.out.println("运行结果："+i);
		}
	}

	//实现Runnable
	public static class Runable01 implements Runnable{
		@Override
		public void run(){
			System.out.println("当前线程："+Thread.currentThread().getId());
			int i = 10/2;
			System.out.println("运行结果："+i);
		}
	}

	//实现Callable
	public static class Callable01 implements Callable<Integer>{
		@Override
		public Integer call() throws Exception {
				System.out.println("当前线程："+Thread.currentThread().getId());
				int i = 10/2;
				return i;
		}
	}
}
